import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Router, ActivatedRoute } from '@angular/router';
import { CommonService } from '../../../services-common/common.service';
import { changeCodeStatusArrs } from '../status.pipe';
import { SellChangecodeRecordService } from './sell-changecode-record.service';

@Component({
  selector: 'app-sell-changecode-record',
  templateUrl: './sell-changecode-record.component.html',
  styleUrls: ['./sell-changecode-record.component.scss']
})
export class SellChangecodeRecordComponent implements OnInit {

  routeParams: any = {};
  searchOptions = [
    { type: 1, labelText: '券包ID', valueKey: 'packageId', value: '' },
    { type: 1, labelText: '批次号', valueKey: 'lotNo', value: '' },
    { type: 1, labelText: '关联用户优惠券', valueKey: 'userRecordId', value: '' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'status',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...changeCodeStatusArrs],
    },
    { type: 3, labelText: '生成时间', valueKey: ['createTime', 'createTime2'], value: [], isTimeSelect: true },
    { type: 3, labelText: '兑换时间', valueKey: ['exchangeTime', 'exchangeTime2'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  // 作废
  isVoidVisible = false;
  toVoidForms = {
    loading: false,
    lotNo: ''
  }

  exportLoading = false;

  constructor(
    private message: NzMessageService,
    private modal: NzModalService,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private services: SellChangecodeRecordService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
      this.searchOptions[0].value = this.commonService.isEmpty(res.couponBagId) ? '' : res.couponBagId;
    })
  }

  ngOnInit(): void {
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getChangeCodeList(params);
    this.tableParams.loading = false;

    if (code === 0) {
      this.tableParams.tableData = data.records || [];
      this.tableParams.total = data.total || 0;
    } else {
      this.message.error(message);
    }
  }

  queryResetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  exportTable() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的订单数据，为了导出速度请尽可能控制时间范围。确定导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        this.exportLoading = true;
        const res: any = await this.services.exportChangeCodeData({...this.searchParams});
        this.exportLoading = false;

        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '兑换码记录');
        } else {
          this.message.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  showBatchModal() {
    this.toVoidForms.lotNo = '';
    this.isVoidVisible = true;
  }

  async submitBatchVoid() {
    if (this.commonService.isEmpty(this.toVoidForms.lotNo)) {
      this.message.warning('请输入批次号');
      return
    }

    // 根据批次号统计兑换码信息
    let infoParams = {
      lotNo: this.toVoidForms.lotNo
    }
    const infoId = this.message.loading('正在请求兑换码信息..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.getChangeCodeInfoData(infoParams);
    this.message.remove(infoId);
    
    if (code === 0) {
      this.modal.confirm({
        nzTitle: '提示',
        nzContent: `
          <p>本次<b>${data.total}</b>个兑换码</p>
          <p>其中<b>${data.unExchangeCount}</b>个未兑换，<b>${data.exchangedCount}</b>个已兑换</p>
          <p><b>${data.expiredCount}</b>个已过期，<b>${data.canceledCount}</b>个已作废</p>
          <p class="p-t-10">确认将这些<b class="mred-text">未兑换</b>的作废?作废以后这些券码将<b class="mred-text">无法兑换</b></p>
        `,
        nzOkText: '确认',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: () => {
          this.voidCodeInterface({lotNo: this.toVoidForms.lotNo});
        },
        nzCancelText: '取消'
      });
    } else {
      this.message.error(message);
    }
  }

  singleVoid(item: any) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认作废本兑换码吗？作废以后该券码将无法兑换',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.voidCodeInterface({id: item.id});
      },
      nzCancelText: '取消'
    });
  }

  async voidCodeInterface(params: {id?: number, lotNo?: number | string}) {
    const res: any = await this.services.cancelChangeCodeData(params);
    if (res.code === 0) {
      this.isVoidVisible = false;
      this.message.success('操作成功');
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }
}
